package com.hsj.goldstore.mvp.present;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.hsj.goldstore.R;
import com.hsj.goldstore.base.BaseMvpPresent;
import com.hsj.goldstore.base.ResultCallback;
import com.hsj.goldstore.mvp.model.LoginModel;
import com.hsj.goldstore.mvp.view.MainView;
import com.hsj.goldstore.mvp.view.fragment.GoldStoreFragment;
import com.hsj.goldstore.mvp.view.fragment.GoodsFragment;
import com.hsj.goldstore.mvp.view.fragment.MyFragment;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by Administrator on 2018/3/21.
 */

public class MainPresent extends BaseMvpPresent<MainView> implements IMainPresent {
    private LoginModel loginModel;
    private ArrayList<String> fragmentTags = new ArrayList<>(Arrays.asList("GoldStoreFragment"
            , "GoodsFragment", "MyFragment"));
    private int index;
    private FragmentManager manager;

    public MainPresent() {
        loginModel = new LoginModel();
    }


    public void init() {
        //检查是否绑定view
        checkViewAttach();
        manager = mvpView.getManager();
    }


    private void showFragment() {
        FragmentTransaction fragmentTransaction = manager.beginTransaction();

        Fragment fragment = manager.findFragmentByTag(fragmentTags.get(index));
        if (null == fragment) {
            fragment = instantFragment();
        }
        for (int i = 0; i < fragmentTags.size(); i++) {
            Fragment f = manager.findFragmentByTag(fragmentTags.get(i));
            if (null != f && f.isAdded()) {
                fragmentTransaction.hide(f);
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.fragment, fragment, fragmentTags.get(index));
        }
        fragmentTransaction.commitAllowingStateLoss();
        manager.executePendingTransactions();

    }

    private Fragment instantFragment() {
        switch (index) {
            case 0:
                return new GoldStoreFragment();
            case 1:
                return new GoodsFragment();
            case 2:
                return new MyFragment();
            default:
                return null;
        }
    }

    @Override
    public void showStore() {
        index = 0;
        showFragment();
    }

    @Override
    public void showGoods() {
        index = 1;
        showFragment();
    }

    @Override
    public void showMy() {
        index = 2;
        showFragment();
    }

}
